Chapter 12: Authentication – Log In Tokens

We have implemented signing up of a new user, and generating a new token for them. But how do we retrieve a

token for an existing user who logs in?

Let’s first create a url for them to login and retrieve a token. In todobackend/api/urls.py, create the path:

Modify Bold Code

from django.urls import path

from . import views

urlpatterns = [

path('todos/', views.TodoListCreate.as_view()),

path('todos/<int:pk>', views.TodoRetrieveUpdateDestroy.as_view()),

path('todos/<int:pk>/complete', views.TodoToggleComplete.as_view()),

path('signup/', views.signup),

path('login/', views.login),

]

We next implement the login view in todobackend/api/views.py:

Modify Bold Code

...

from django.views.decorators.csrf import csrf_exempt

from django.contrib.auth import authenticate

...

@csrf_exempt

def signup(request):

...

@csrf_exempt

def login(request):

if request.method == 'POST':

data = JSONParser().parse(request)

user = authenticate(

request,

username=data['username'],

password=data['password'])

if user is None:

return JsonResponse(

{'error':'unable to login. check username and password'},

status=400)

else: # return user token

try:

token = Token.objects.get(user=user)

except: # if token not in db, create a new one

token = Token.objects.create(user=user)

return JsonResponse({'token':str(token)}, status=201)

Code Explanation

The code in general is similar to sign up.

Analyze Code

def login(request):

if request.method == 'POST':

We check if a request was performed using the HTTP ‘POST’ method because the login form in the front end will

use POST requests for form submissions.

Analyze Code

data = JSONParser().parse(request)

user = authenticate(

request,

username=data['username'],

password=data['password'])

We then call JSONParse().parse to parse the JSON request content and return a dictionary of data.

We extract the user filled-in values from the dictionary with data[‘username’] and data[‘password’] and pass them

into the authenticate method.

Analyze Code

if user is None: